import cookie from 'js-cookie';
import cookieKeys from '../const/cookie-keys';
import {
  loginLoginByCode,
  loginLoginByPhone,
  getCurrAppResource,
  getCurrentCompanyList,
  chooseCompany,
  getBasicResourceListByAppCode
} from '../const/api_staffCenter.js';

const cookiePath = process.env.COOKIE_PATH;
// 企业类型 是否医院
const ROLE_TYPE = {
  AG: '0', // 经营企业
  HO: '1', // 医疗机构
  FC: '2', // 原厂
  SV: '3', // 服务商
  '-1': '-1' // 系统管理员
};
// 校验是否已经通过
function resetData(userDetail) {
  // 0-第一次发起，1-通过，2-第一个发起驳回，3-通过后的待审核，4-通过后的驳回
  if (
    userDetail.approveStatus === null ||
    Number(userDetail.approveStatus) === 0 ||
    Number(userDetail.approveStatus) === 2
  ) {
    userDetail.authenticateFlag = false;
  } else {
    userDetail.authenticateFlag = true;
  }
  return userDetail;
}

// 最好提前在你的 store 中初始化好所有所需属性
// https://vuex.vuejs.org/zh-cn/mutations.html
export const state = () => ({
  appId: cookie.get('appId') || 0, // appid用来选择系统后，用于获取并展示菜单
  MID: cookie.get('MID') || 0,
  structureLogo: '', // 体系logo
  factoryCompanyId: '', // 原厂id
  positionList: [], // 岗位
  positionLists: [], // 岗位
  positionCompanyName: '', // 登录人当前公司
  positionName: '', // 登录人当前岗位
  positionId: '', // 登录人当前id
  // 这两个用于client side的使用, 又放cookie里是为了刷新时状态不丢失
  tableHeadConfig: null, // 记录用户自定义表头的json
  meta: {},
  menuList: [],
  layoutHandle: {}, // 面包屑右侧的方法回调
  activeNameArr: [], // 路由守卫根据id计算出来的地址，用于面包屑
  isDeepPage: false, // 记录是否深层页面
  btnRoleArr: [], // 记录该用户所有的权限按钮
  activeIndex: 0, // 顶部一级菜单, 面包屑还需要，所以提到全局，并不能在menuList加路由层级，因为，nuxt已经生成路由
  // 与cookie-key关联的内容
  token: '',
  userId: '',
  tenantId: '',
  approveStatus: '',
  authenticateFlag: '',
  companyCode: '',
  companyId: '',
  companyName: '',
  companyType: '',
  realName: '', // 后端写错了，将错就错
  userCode: '',
  userName: '',
  loginUserName: '',
  appName: '',
  appPathName: '',
  topNavIndex: 0,
  menuListTopNav: [],
  ifAdmin: '', // 是否管理员工
  avatar: '', // 头像
  toNavPage:
    process.env.NODE_ENV === 'development'
      ? 'http://localhost:3001/#/'
      : window.location.origin + '/#/',
  isShowLeftMenu: true,
  layoutLoginPageTitle: '',
  randomCode: '', // 滑动滑后端返回的随机数
  moveTime: 0, //滑块滑动时间
  password: '',
  
})

//  mutation 必须同步执行
export const mutations = {
  setLoginTitle(state, payload) {
    console.log(payload)
    state.layoutLoginPageTitle = payload
  },
  // 根据传过来的值，判断是否显示左侧的菜单（主要使用在m-door的考试系统）
  changeIsShowLeftMenu(state, index) {
    state.isShowLeftMenu = index
  },
  login(state, payload) {
    let newData = resetData(payload);
    // 部署不一定是在根路径, 所以cookie要设置path
    state.ifAdmin = newData.ifAdmin
    cookie.set('ifAdmin', newData['ifAdmin'], {
      path: cookiePath
    })
    state.avatar = newData.avatar
    cookie.set('avatar', newData['avatar'], {
      path: cookiePath
    })
    cookieKeys.forEach(key => {
      // 判断是否是医院
      if (key === 'roleType') {
        state['roleType'] = ROLE_TYPE[newData['companyType']];
        // 存在bug，设置后forEach不执行了
        cookie.set(key, state['roleType'], {
          path: cookiePath
        })
      }
      else if (key === 'realName') {
        // 兼容数据错误
        state[key] = newData['relaName'];
        cookie.set(key, newData['relaName'], {
          path: cookiePath
        })
      }
      else {
        state[key] = newData[key]
        cookie.set(key, newData[key], {
          path: cookiePath
        });
      }
    });
  },

  logout(state) {
    // 清空菜单，防止菜单记录
    state.menuList = [];
    // 清空用户操作历史
    sessionStorage.removeItem('USER_HISTORY');
    // 遍历清空cookie的内容
    cookieKeys.forEach(key => {
      state[key] = '';
      cookie.remove(key, {
        path: cookiePath
      });
    });
  },

  getPositionList(state, payload) {
    state.positionList = payload;
    let arr = [];
    payload.forEach((item, index) => {
      if (item.ifLast) {
        state.positionCompanyName = item.companyName;
        state.positionName = item.positionName;
        state.positionId = item.companyId;
      }
      let obj = {
        // label: item.companyName + ' ' + item.positionName,
        label: item.companyName,
        value: item.companyId
      };
      arr.push(obj);
    });
    state.positionLists = arr;
    console.log(state.positionLists, '------')
  },

  reSetPwd() {
    this.$router.replace(`/login/retrieve?reset=true&name=${this.state.loginUserName}`);
  },

  loginUserName(state, loginUserName) {
    state.loginUserName = loginUserName;
  },

  update(state, payload) {
    console.log(payload, '177')
    Object.keys(payload).forEach(k => {
      state[k] = payload[k];
    });
  },
  // 添加面包屑右侧方法
  changeLayoutHandle(state, obj) {
    state.layoutHandle = obj;
  },
  setAppId(state, str) {
    state.appId = str;
    cookie.set('appId', str);
  },
  setStructureLogo(state, str) {
    state.structureLogo = str;
    cookie.set('structureLogo', str);
  },
  setFactoryCompanyId(state, str) {
    state.factoryCompanyId = str;
    cookie.set('factoryCompanyId', str);
  },
  // 修改一级菜单的下标
  changeActiveIndex(state, index) {
    state.activeIndex = index;
  },
  changeTopNavIndex(state, index) {
    state.topNavIndex = index;
  },
  changeMenuListTopNav(state, list) {
    state.menuListTopNav = list;
  },
  // 记录当前导航的层级的数组
  changeActiveNameArr(state, arr) {
    // 切割掉顶部一级的导航
    state.activeNameArr = arr.slice(1);
    // state.activeNameArr = arr
    // 保留末级节点
    // state.activeNameArr = [arr[arr.length - 1]]
  },
  // 记录用户自定义表头
  tableHeadConfig(state, { json, path }) {
    // 如果没有path则标识刷新或者刚登陆状态
    if (!path) {
      state.tableHeadConfig = json;
    } else {
      // 如果不是null
      if (state.tableHeadConfig) {
        state.tableHeadConfig = { ...state.tableHeadConfig, [path]: json };
      } else {
        state.tableHeadConfig = {
          [path]: json
        };
      }
      localStorage.setItem('testKey', JSON.stringify(state.tableHeadConfig));
    }
  },
  // 推入全局，按钮级权限控制
  pushRoleArr(state, str) {
    state.btnRoleArr.push(str);
  },
  // 记录是否是深层页面
  isDeepPage(state, flag) {
    state.isDeepPage = flag;
  },
  // 设置选中页面
  setAppPathName(state, url) {
    state.appPathName = url.url1;
  },
  randomCode (state, payload) {
    state.randomCode = payload
  },
  moveTime (state, payload) {
    state.moveTime = payload
  },
  password(state, password) {
    state.password = password;
  }
};

// Action 提交的是 mutation，而不是直接变更状态
// Action 可以包含任意异步操作
export const actions = {
  login({ commit }, { isPassword, ...obj }) {
    return new Promise((resolve, reject) => {
      this.$axios({
        url: isPassword ? loginLoginByCode : loginLoginByPhone,
        method: 'post',
        data: obj
      })
        .then(res => {
          commit('login', res.data.payload || {});
          cookie.remove('appId', {
            path: cookiePath
          })
          resolve(res)//成功时的返回值，this.$store.dispatch.then(res)用
        })
        .catch(err => {
          reject(err);
        });
    });
  },
  // 获取岗位列表
  getPositionList({ commit }) {
    this.$axios({
      url: getCurrentCompanyList,
      method: 'post'
    })
      .then(res => {
        commit('getPositionList', res.data.payload || {});
      })
      .catch(err => {
        console.log(err);
      });
  },
  choosePosition({ commit }, { item }) {
    console.log(item,'----item')
    this.$axios({
      url: chooseCompany,
      method: 'post',
      headers: { 'Content-Type': 'application/json;charset=UTF-8' },
      data: { companyId: item.positionId }
    })
      .then(res => {
        commit('login', res.data.payload || {});
        window.location.href = '/';
        // this.$router.replace('/')
      })
      .catch(err => {
        console.log(err);
      });
  },
  // 存储权限按钮集合,记录该成员拥有的按钮级权限
  pushRoleArr({ commit }, str) {
    commit('pushRoleArr', str);
  },
  async fetchUserAndMenuList({ commit }) {
    let menuResources = await this.$axios.$post(getCurrAppResource, {
      appId:
        this.state.appId === undefined || this.state.appId === null || this.state.appId === '' ? '0' : this.state.appId
    });
    // 给获取到的菜单进行id赋值
    // 赋key，val用于反向选中菜单
    let list = [];
    if (menuResources.payload) {
      list = menuResources.payload;
    }
    function iterator(list = [], id = '', supParentIndex) {
      list.forEach((item, index) => {
        item.idKey = !id ? String(index) : id + '-' + index;
        item.supParentIndex = supParentIndex || String(index);
        // 如果层级不等于2，则将iconUrl重置为空
        if (item.idKey.split('-').length !== 2) {
          item.iconUrl = '';
        }
        if (item.children && item.children.length) {
          iterator(item.children, item.idKey, item.supParentIndex);
        }
      });
    }
    iterator(list);

    commit('update', {
      menuList: list
    });
    let clist = this.state.menuList;
    clist.forEach((item, index) => {
      item.menuSort = index;
    });
    commit('changeMenuListTopNav', clist);
  },
  // 企业中心改版后，需要获取默认的子系统从而进行跳转
  /* 
    暂时的可选值：COMPANY_AUTH_BASIC（企业认证）、E_SIGNATURE_BASIC（电子签章管理）、COMPANY_MANAGE_BASIC（企业信息管理）、ACCOUNT_MANAGE_BASIC（账号管理）
  */ 
  async fetchDefaultMenuList({ commit }, appCode) {
    let menuResources = await this.$axios.$post(getBasicResourceListByAppCode, { appCode: appCode });
    console.log(menuResources,'menuResources')
    // 给获取到的菜单进行id赋值
    // 赋key，val用于反向选中菜单
    let list = [];
    if (menuResources.payload) {
      list = menuResources.payload;
    }
    function iterator(list = [], id = '', supParentIndex) {
      list.forEach((item, index) => {
        item.idKey = !id ? String(index) : id + '-' + index;
        item.supParentIndex = supParentIndex || String(index);
        // 如果层级不等于2，则将iconUrl重置为空
        if (item.idKey.split('-').length !== 2) {
          item.iconUrl = '';
        }
        if (item.children && item.children.length) {
          iterator(item.children, item.idKey, item.supParentIndex);
        }
      });
    }
    iterator(list);

    commit('update', {
      menuList: list
    });
    let clist = this.state.menuList;
    clist.forEach((item, index) => {
      item.menuSort = index;
    });
    commit('changeMenuListTopNav', clist);
  }
};
